<?php

namespace App\Http\Controllers\Admin;

use App\Http\Requests\FangattrRequest;
use App\Models\Fangattr;
use Illuminate\Http\Request;

class FangattrController extends BaseController
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Fangattr $fangattr)
    {
        //取出房源属性数据
        $data = Fangattr::get()->toArray();
        $data = treeLevel($data);
        return view('admin.fangattr.index', compact('fangattr', 'data'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //获取所有顶级房源属性
        $pData = Fangattr::where('pid', 0)->get();
        return view('admin.fangattr.create', compact('pData'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(FangattrRequest $request)
    {
        //接收数据入库
        $data=$request->except(['_token', 'file']);
        $data['field_name']=!empty($data['field_name'])?$data['field_name']:'';
        Fangattr::create($data);
        return redirect(route('admin.fangattr.index'))->with('success', '添加成功');
    }

    /**
     * Display the specified resource.
     *
     * @param \App\Models\Fangattr $fangattr
     * @return \Illuminate\Http\Response
     */
    public function show(Fangattr $fangattr)
    {
        //
    }

    //修改显示  传递的ID进行路由参数的隐式转换为对应的模型
    public function edit(Fangattr $fangattr)
    {
        //获取所有的顶级属性
        $pData = Fangattr::where('pid', 0)->get();
        //指定视图模版关联显示
        return view('admin.fangattr.edit', compact('pData', 'fangattr'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param \Illuminate\Http\Request $request
     * @param \App\Models\Fangattr $fangattr
     * @return \Illuminate\Http\Response
     */
    public function update(FangattrRequest $request, Fangattr $fangattr)
    {
        //接收数据入库
        $data = $request->except(['_token', 'file', '_method']);
        //更新最新的数据导数据表，更新时因为field_name字段不能为null
        //而field_name不是所有记录都要填写,需要单独处理
        $fangattr->update($data);
        //成功后跳转列表页
        return redirect(route("admin.fangattr.index"))->with('success', '修改成功');
    }
    public function delpic(Request $request)
    {
        //删除图片操作
        $path=$request->get('path');
        $filepath=public_path($path);
        //判断此文件是否存在，存在则删除
        if(file_exists($filepath)){
            unlink($filepath);
        }
        //修改数据表
        Fangattr::where('id',$request->get('id'))->update(['icon'=>'']);
        return ['code'=>0,'msg'=>'修改成功'];
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param \App\Models\Fangattr $fangattr
     * @return \Illuminate\Http\Response
     */
    public function destroy(Fangattr $fangattr)
    {
        //
    }
}
